<template>
  <div class="echarts">
    <div class="unit" v-if="unit">单位：{{ unit }}</div>
    <ECharts :option="option" :on-click="clickBar" />
  </div>
</template>

<script setup lang="ts" name="BarEcharts">
import ECharts from "@/components/ECharts/index.vue";
import { onMounted, reactive, watch } from "vue";

const props = defineProps({
  data: {
    type: Array,
    required: false,
    default: () => []
  },
  colorList: {
    type: Array,
    required: false,
    default: () => []
  },
  name: {
    type: String,
    required: false,
    default: ""
  },
  unit: {
    type: String,
    required: false
  }
});

const option: any = reactive({
  // title: {
  //   text: "单位：元",
  //   textStyle: {
  //     // color: "#a1a1a1",
  //     fontSize: 12,
  //     top: 10
  //   }
  // },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      label: {
        backgroundColor: "#6a7985"
      }
    }
  },
  // toolbox: {
  //   feature: {
  //     saveAsImage: {}
  //   }
  // },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "3%",
    top: "18%",
    containLabel: true
  },
  legend: {
    data: ["使用量", "剩余量"],
    right: "20px",
    icon: "rect",
    itemWidth: 16, // 设置图例图标的宽度
    itemHeight: 16, // 设置图例图标的高度
    itemGap: 30 // 设置图例项之间的间距
  },
  xAxis: [
    {
      type: "category",
      // boundaryGap: false,
      data: [],
      axisLabel: {
        color: "#a1a1a1"
      },
      axisTick: { show: false }
    }
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {
        color: "#a1a1a1"
      }
    }
  ],
  series: [
    {
      name: "使用量",
      type: "bar",
      stack: "one",
      emphasis: {
        focus: "series"
      },
      data: [],
      barWidth: 20
    },
    {
      name: "剩余量",
      type: "bar",
      stack: "one",
      emphasis: {
        focus: "series"
      },
      data: [],
      barWidth: 20
    }
  ]
});

const setOption = () => {
  const data: any = props.data || [];
  // const name = props.name || "";
  // option.xAxis[0].data = data.map(a => a.name);
  // option.series[0].data = data.map(a => a.use);
  // option.series[1].data = data.map(a => a.nouse);
  option.xAxis[0].data = [];
  option.series[0].data = [];
  option.series[1].data = [];
  const total: number[] = [];
  const usageRate: number[] = [];
  const nousageRate: number[] = [];
  data.forEach(item => {
    const use: number = item.use || 0;
    const nouse: number = item.nouse || 0;
    option.xAxis[0].data.push(item.name);
    option.series[0].data.push(use);
    option.series[1].data.push(nouse);
    const sum: number = use + nouse;
    total.push(sum);
    usageRate.push(sum ? Math.round((use / sum) * 100) : 0);
    nousageRate.push(sum ? Math.round((nouse / sum) * 100) : 0);
  });
  if (total.length) {
    option.tooltip.formatter = function (params) {
      const i = params[0].dataIndex;
      let tooltipContent = `
        <div>
        <div style="display:inline-block;width:90px;">${params[0].name}</div>
        <div style="display:inline-block;">总量：${total[i]}</div>
        </div>
      `;
      const rate = [usageRate[i], nousageRate[i]];
      params.forEach(function (item, index) {
        // 添加其他自定义内容
        tooltipContent += `
          <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${item.color};"></span>
          <div style="display:inline-block;">${item.seriesName}: <div style="display:inline-block;width:50px;margin-right: 6px">${item.value}</div>${rate[index]}%</div><br>
        `;
        if (index === 1 && rate[index] <= 10) {
          tooltipContent += `
            <br>剩余率不足10%
          `;
        }
      });

      return tooltipContent;
    };
    option.series[1].itemStyle = {
      normal: {
        // 标记点样式
        color: function (params) {
          const i = params.dataIndex;
          // 判断数据值是否小于60，如果是，则标红
          return nousageRate[i] < 10 ? "#F6302FFF" : params.color;
        }
      }
    };
  }
  if (props.colorList && props.colorList.length) {
    option.color = props.colorList;
  }
};
const emit = defineEmits(["clickBar"]);
const clickBar = e => {
  emit("clickBar", props.name, e.name);
};
watch(
  () => props.data,
  () => {
    setOption();
  }
);

onMounted(() => {
  setOption();
});
</script>

<style scoped lang="scss">
.echarts {
  position: relative;
  width: 100%;
  height: 100%;
  .unit {
    position: absolute;
    top: 8px;
    left: 0;
    font-size: 12px;
    color: var(--el-text-color-primary);
  }
}
</style>
